import React, { useState } from 'react';
import {
  Modal,
  View,
  StyleSheet,
  TouchableOpacity,
  TextInput,
  Image,
  Platform,
  ScrollView,
  ActivityIndicator,
} from 'react-native';
import { ThemedText } from './ThemedText';
import { FontAwesome } from '@expo/vector-icons';
import * as ImagePicker from 'expo-image-picker';
import * as FileSystem from 'expo-file-system';
import { LinearGradient } from 'expo-linear-gradient';
import { fetchDishes } from '@/data/dishes';
import * as ImageManipulator from 'expo-image-manipulator';

type Props = {
  visible: boolean;
  onClose: () => void;
  onSuccess: () => void;
};

const TAGS = ['荤菜', '素菜', '甜食', '主食', '水果'];

const AddDishModal = ({ visible, onClose, onSuccess }: Props) => {
  const [name, setName] = useState('');
  const [price, setPrice] = useState('');
  const [selectedTags, setSelectedTags] = useState<string[]>([]);
  const [imageUri, setImageUri] = useState('');
  const [isLoading, setIsLoading] = useState(false);
  const [error, setError] = useState('');

  const handleSelectImage = async () => {
    try {
      const result = await ImagePicker.launchImageLibraryAsync({
        mediaTypes: ImagePicker.MediaTypeOptions.Images,
        allowsEditing: true,
        aspect: [1, 1],
        quality: 1,  // 先保持原始质量，后面再压缩
      });

      if (!result.canceled && result.assets[0]) {
        const asset = result.assets[0];
        
        try {
          // 压缩图片
          const manipulatedImage = await ImageManipulator.manipulateAsync(
            asset.uri,
            [
              { resize: { width: 500, height: 500 } }
            ],
            {
              compress: 0.2,  // 压缩质量 (0-1)
              format: ImageManipulator.SaveFormat.JPEG
            }
          );

          setImageUri(manipulatedImage.uri);
          
          // 检查压缩后的大小
          const fileInfo = await FileSystem.getInfoAsync(manipulatedImage.uri, { size: true });
          if (fileInfo.exists && fileInfo.size) {
            const sizeInKB = fileInfo.size / 1024;
            console.log('Compressed image size:', sizeInKB.toFixed(2) + 'KB');
            
            if (sizeInKB > 200) {
              setError('图片较大，可能会影响上传速度');
            }
          }
        } catch (err) {
          console.error('Error compressing image:', err);
          setError('图片压缩失败');
        }
      }
    } catch (err) {
      console.error('Error picking image:', err);
      setError('选择图片失败');
    }
  };

  const handleToggleTag = (tag: string) => {
    setSelectedTags(prev => 
      prev.includes(tag)
        ? prev.filter(t => t !== tag)
        : [...prev, tag]
    );
  };

  const handleSubmit = async () => {
    try {
      setIsLoading(true);
      setError('');

      if (!name || !price || !imageUri || selectedTags.length === 0) {
        throw new Error('请填写完整信息');
      }

      // 1. 上传图片
      try {
        // 获取图片信息
        const fileInfo = await FileSystem.getInfoAsync(imageUri, { size: true });
        if (fileInfo.exists && fileInfo.size) {
          const sizeInKB = fileInfo.size / 1024;
          console.log('Upload image size:', sizeInKB.toFixed(2) + 'KB');
          
          if (sizeInKB > 512) {
            console.warn('Image size larger than 500KB:', sizeInKB.toFixed(2) + 'KB');
          }
        }

        const uploadResult = await FileSystem.uploadAsync(
          'http://116.205.137.46/api/upload',
          imageUri,
          {
            fieldName: 'file',
            httpMethod: 'POST',
            uploadType: FileSystem.FileSystemUploadType.MULTIPART,
            mimeType: 'image/jpeg'
          }
        );

        if (uploadResult.status !== 200) {
          console.error('Upload response:', uploadResult.body);
          throw new Error('图片上传失败');
        }

        const { url } = JSON.parse(uploadResult.body);

        // 2. 添加菜品
        const dishResponse = await fetch('http://116.205.137.46/api/dishes', {
          method: 'POST',
          headers: {
            'Content-Type': 'application/json',
          },
          body: JSON.stringify({
            name,
            price: Number(price),
            image: url,
            tags: selectedTags,
          }),
        });

        if (!dishResponse.ok) {
          throw new Error('添加菜品失败');
        }

        // 3. 重新获取菜品列表
        await fetchDishes();
        
        onSuccess();
        handleClose();
      } catch (err) {
        console.error('Error submitting dish:', err);
        setError(err instanceof Error ? err.message : '添加失败');
      } finally {
        setIsLoading(false);
      }
    } catch (err) {
      console.error('Error submitting dish:', err);
      setError(err instanceof Error ? err.message : '添加失败');
    }
  };

  const handleClose = () => {
    setName('');
    setPrice('');
    setSelectedTags([]);
    setImageUri('');
    setError('');
    onClose();
  };

  return (
    <Modal
      visible={visible}
      transparent
      animationType="fade"
      onRequestClose={handleClose}
    >
      <View style={styles.overlay}>
        <View style={styles.container}>
          <View style={styles.header}>
            <ThemedText style={styles.title}>添加菜品</ThemedText>
            <TouchableOpacity 
              style={styles.closeButton}
              onPress={handleClose}
              disabled={isLoading}
            >
              <FontAwesome name="close" size={20} color="#666" />
            </TouchableOpacity>
          </View>

          <ScrollView style={styles.content}>
            <TouchableOpacity 
              style={styles.imageUpload}
              onPress={handleSelectImage}
              disabled={isLoading}
            >
              {imageUri ? (
                <Image source={{ uri: imageUri }} style={styles.previewImage} />
              ) : (
                <View style={styles.uploadPlaceholder}>
                  <FontAwesome name="camera" size={32} color="#999" />
                  <ThemedText style={styles.uploadText}>点击选择图片</ThemedText>
                </View>
              )}
            </TouchableOpacity>

            <View style={styles.inputGroup}>
              <ThemedText style={styles.label}>菜品名称</ThemedText>
              <TextInput
                style={styles.input}
                value={name}
                onChangeText={setName}
                placeholder="请输入菜品名称"
                placeholderTextColor="#999"
                editable={!isLoading}
              />
            </View>

            <View style={styles.inputGroup}>
              <ThemedText style={styles.label}>价格</ThemedText>
              <TextInput
                style={styles.input}
                value={price}
                onChangeText={setPrice}
                placeholder="请输入价格"
                placeholderTextColor="#999"
                keyboardType="numeric"
                editable={!isLoading}
              />
            </View>

            <View style={styles.inputGroup}>
              <ThemedText style={styles.label}>标签</ThemedText>
              <View style={styles.tags}>
                {TAGS.map(tag => (
                  <TouchableOpacity
                    key={tag}
                    style={[
                      styles.tag,
                      selectedTags.includes(tag) && styles.tagSelected
                    ]}
                    onPress={() => handleToggleTag(tag)}
                    disabled={isLoading}
                  >
                    <ThemedText 
                      style={[
                        styles.tagText,
                        selectedTags.includes(tag) && styles.tagTextSelected
                      ]}
                    >
                      {tag}
                    </ThemedText>
                  </TouchableOpacity>
                ))}
              </View>
            </View>

            {error ? (
              <ThemedText style={styles.error}>{error}</ThemedText>
            ) : null}
          </ScrollView>

          <View style={styles.footer}>
            <TouchableOpacity
              style={[styles.button, styles.cancelButton]}
              onPress={handleClose}
              disabled={isLoading}
            >
              <ThemedText style={styles.buttonText}>取消</ThemedText>
            </TouchableOpacity>
            <TouchableOpacity
              style={[styles.button, styles.submitButton]}
              onPress={handleSubmit}
              disabled={isLoading}
            >
              <LinearGradient
                colors={['#FF9F45', '#FFC288'] as const}
                start={{ x: 0, y: 0 }}
                end={{ x: 1, y: 0 }}
                style={styles.submitGradient}
              >
                {isLoading ? (
                  <ActivityIndicator color="#fff" size="small" />
                ) : (
                  <ThemedText style={styles.submitText}>确认添加</ThemedText>
                )}
              </LinearGradient>
            </TouchableOpacity>
          </View>
        </View>
      </View>
    </Modal>
  );
};

const styles = StyleSheet.create({
  overlay: {
    flex: 1,
    backgroundColor: 'rgba(0, 0, 0, 0.4)',
    justifyContent: 'center',
    alignItems: 'center',
  },
  container: {
    width: '90%',
    maxHeight: '90%',
    backgroundColor: '#fff',
    borderRadius: 16,
    overflow: 'hidden',
    shadowColor: '#000',
    shadowOffset: { width: 0, height: 4 },
    shadowOpacity: 0.15,
    shadowRadius: 12,
    elevation: 8,
  },
  header: {
    flexDirection: 'row',
    justifyContent: 'center',
    alignItems: 'center',
    padding: 16,
    borderBottomWidth: 1,
    borderBottomColor: '#eee',
    position: 'relative',
  },
  title: {
    fontSize: 18,
    fontWeight: 'bold',
    color: '#333',
  },
  closeButton: {
    position: 'absolute',
    right: 16,
    width: 32,
    height: 32,
    borderRadius: 16,
    backgroundColor: '#f5f5f5',
    justifyContent: 'center',
    alignItems: 'center',
  },
  content: {
    padding: 16,
  },
  imageUpload: {
    width: '100%',
    height: 200,
    borderRadius: 12,
    backgroundColor: '#f5f5f5',
    marginBottom: 16,
    overflow: 'hidden',
  },
  previewImage: {
    width: '100%',
    height: '100%',
    resizeMode: 'cover',
  },
  uploadPlaceholder: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
  },
  uploadText: {
    marginTop: 8,
    fontSize: 14,
    color: '#999',
  },
  inputGroup: {
    marginBottom: 16,
  },
  label: {
    fontSize: 14,
    color: '#666',
    marginBottom: 8,
  },
  input: {
    height: 44,
    borderWidth: 1,
    borderColor: '#ddd',
    borderRadius: 8,
    paddingHorizontal: 12,
    fontSize: 16,
    color: '#333',
  },
  tags: {
    flexDirection: 'row',
    flexWrap: 'wrap',
    gap: 8,
  },
  tag: {
    paddingVertical: 6,
    paddingHorizontal: 12,
    borderRadius: 16,
    backgroundColor: '#f5f5f5',
  },
  tagSelected: {
    backgroundColor: '#FFF0E6',
  },
  tagText: {
    fontSize: 14,
    color: '#666',
  },
  tagTextSelected: {
    color: '#FF9F45',
  },
  error: {
    color: '#ff4d4f',
    fontSize: 14,
    marginTop: 8,
    textAlign: 'center',
  },
  footer: {
    flexDirection: 'row',
    padding: 16,
    gap: 12,
    borderTopWidth: 1,
    borderTopColor: '#eee',
  },
  button: {
    flex: 1,
    height: 44,
    borderRadius: 22,
    overflow: 'hidden',
  },
  cancelButton: {
    backgroundColor: '#f5f5f5',
    justifyContent: 'center',
    alignItems: 'center',
  },
  submitButton: {
    backgroundColor: '#FF9F45',
  },
  submitGradient: {
    width: '100%',
    height: '100%',
    justifyContent: 'center',
    alignItems: 'center',
  },
  buttonText: {
    fontSize: 16,
    color: '#666',
  },
  submitText: {
    fontSize: 16,
    color: '#fff',
    fontWeight: '600',
  },
});

export default AddDishModal; 